package com.powernode.service.impl;

import com.powernode.constant.AuthConstant;
import com.powernode.ex.AuthException;
import com.powernode.factory.LoginStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author LF
 * projectName:today-shop
 * description:
 * time:2022-09-16 22:40
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if(!StringUtils.hasText(loginType)){
            throw new AuthException("登陆类型不匹配,非法登陆");
        }
        // 策略模式 对修改关闭 对拓展开放
        return loginStrategyFactory.realDoLogin(loginType, username);
    }
}
